import Taro from "@tarojs/taro";
import { useEffect, useState } from "react";

const X_WX_SERVICE = "flask-92sh";

export function useCallContainerGet(path?: string) {
  const [result, setResult] = useState<any>({});
  const [isLoading, setIsLoading] = useState<boolean>(false);
  const [count, setCount] = useState(0);
  
  useEffect(() => {
    if (path === undefined || path === null)  return;
    setIsLoading(true);
    Taro.cloud.callContainer({
      path,
      header: {
        "X-WX-SERVICE": X_WX_SERVICE,
      },
      method: "GET"
    }).then((res) => {
      console.log("useCallContainerGet path:", path ," result: ", res);
      setResult(res.data);
      setIsLoading(false);
    }).catch((err) => {
      console.log("useCallContainerGet error: ", err);
    });
  }, [path, count]);

  const update = () => setCount(count + 1);

  return [result, isLoading, update];
}

export function callContainerPost(path: string, data?: any) {
  return Taro.cloud.callContainer({
    path,
    data,
    header: {
      "X-WX-SERVICE": X_WX_SERVICE,
    },
    method: "POST"
  }).then((res) => {
    console.log("useCallContainerPost path:", path ," result: ", res);
    return res;
  }).catch((err) => {
    console.log("useCallContainerPost error: ", err);
  })
}